import asyncio
import random
from aiogram import Bot, Dispatcher, F, types, Router
from aiogram.filters import Command, CommandStart
from aiogram.enums.dice_emoji import DiceEmoji
from aiogram.types import Message, FSInputFile, ReplyKeyboardRemove
import keyboards
import requests
import json
from datetime import datetime

try:
    with open('db.json', 'r') as db:
        clients_db = json.loads(db.read())
except Exception:
    clients_db = {}


TOKEN = "7412348072:AAHtFC4b7hYkEADZ7DVlLUi8bEC2Ge9xWjE"

user_private_router = Router()
ALLOWED_UPDATES = ['message, edited_message']

bot = Bot(TOKEN)
dp = Dispatcher()

dp.include_router(user_private_router)

# cat = FSInputFile("cat.png")
clients = []


def get_promo_code(num_chars=10):
    code_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    code = ''
    for _ in range(0, num_chars):
        slice_start = random.randint(0, len(code_chars) - 1)
        code += code_chars[slice_start : slice_start + 1]
    return code


@user_private_router.message(CommandStart())
async def start(message: types.Message):
    user_id = str(message.from_user.id)

    attemps = 3
    if user_id in clients_db.keys():
        client = clients_db.get(user_id)
        attemps = client["attemps"]
        if client["attemps"] == 0:
            await message.answer(
                f"У вас закончились попытки, ваш промокод на скидку {client["discount"]}% {client["promo_code"]}"
            )
        elif client["attemps"] != 0 and client["promo_code"]:
            await message.answer(
                f"Вы уже взяли промокод на скидку {client["discount"]}% {client["promo_code"]}"
            )
        else:
            # await message.answer_photo(cat)
            await message.answer(
                f"Давно не виделись. Испытайте удачу. У вас попыток: {attemps}",
                reply_markup=keyboards.play_game_kb,
            )

    if user_id not in clients_db.keys():
        await message.answer(
            f'Получите скидку в нашем магазине. У вас попыток: {attemps}. Для получения скидки жмите кнопку "Принять участие".',
            reply_markup=keyboards.main_kb,
        )


# @user_private_router.message(Command("help"))
# async def start(message: types.Message):
#     await message.answer("/start")


@user_private_router.message(F.text.lower() == "получить скидку")
async def play(message: Message):
    await message.delete()
    await message.answer_dice(DiceEmoji.SLOT_MACHINE)
    user_id = str(message.from_user.id)
    client = clients_db.get(user_id)
    discount = random.randint(1, 10)
    client["discount"] = discount
    attemps = client["attemps"] - 1
    client["attemps"] = attemps

    img = FSInputFile(f"images/{discount}.jpg")
    await message.answer_photo(img, reply_markup=keyboards.choice_kb)

    if client["attemps"] == 0:
        client["promo_code"] = get_promo_code()
        client["discount"] = discount
        await message.answer(
            f"У вас закончились попытки, ваш промокод на скидку {client["discount"]}% {client["promo_code"]}",
            reply_markup=ReplyKeyboardRemove(),
        )

    else:
        await message.answer(f"У вас осталось попыток: {attemps}")

    clients_db.update({user_id: client})

    with open('db.json', 'w') as db:
        db.write(json.dumps(clients_db))


@user_private_router.message(F.text.lower() == "попробовать еще")
async def start(message: Message):
    await message.delete()
    await message.answer_dice(DiceEmoji.SLOT_MACHINE)
    user_id = str(message.from_user.id)
    client = clients_db.get(user_id)
    discount = random.randint(1, 10)
    client["discount"] = discount
    attemps = client["attemps"] - 1
    client["attemps"] = attemps
    img = FSInputFile(f"images/{discount}.jpg")
    await message.answer_photo(img, reply_markup=keyboards.choice_kb)

    if client["attemps"] == 0:
        client["promo_code"] = get_promo_code()
        client["discount"] = discount
        client["promo_date"] = datetime.now().strftime("%d.%m.%Y")
        client["stop_promo"] = int(client["promo_date"][:2]) + 7
        await message.answer(
            f"У вас закончились попытки, ваш промокод на скидку {client["discount"]}% {client["promo_code"]}",
            reply_markup=ReplyKeyboardRemove(),
        )

        client_data = f"имя: {client["first_name"]}\nфамилия: {client["last_name"]}\nid в телеграм: {client["tg_id"]}\nтелефон: {client["phone_number"]}\nскидка: {client["discount"]}%\nпромокод: {client["promo_code"]}\nпромокод выдан: {client["promo_date"]}"
        requests.post(
            f"https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id=-1002223087995&text={client_data}"
        )

    else:
        await message.answer(f"У вас осталось попыток: {attemps}")

    clients_db.update({user_id: client})

    with open('db.json', 'w') as db:
        db.write(json.dumps(clients_db))


@user_private_router.message(F.text.lower() == "забрать скидку")
async def start(message: Message):
    await message.delete()
    user_id = str(message.from_user.id)
    client = clients_db.get(user_id)
    promo_code = get_promo_code()
    client["promo_code"] = promo_code
    client["promo_date"] = datetime.now().strftime("%d.%m.%Y")
    client["stop_promo"] = int(client["promo_date"][:2]) + 7

    await message.answer(
        f"Ваш промокод на скидку {client["discount"]}% {promo_code}",
        reply_markup=ReplyKeyboardRemove(),
    )

    client_data = f"имя: {client["first_name"]}\nфамилия: {client["last_name"]}\nid в телеграм: {client["tg_id"]}\nтелефон: {client["phone_number"]}\nскидка: {client["discount"]}%\nпромокод: {client["promo_code"]}\nпромокод выдан: {client["promo_date"]}"
    requests.post(
        f"https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id=-1002223087995&text={client_data}"
    )

    clients_db.update({user_id: client})
    with open('db.json', 'w') as db:
        db.write(json.dumps(clients_db))


@user_private_router.message(F.contact)
async def get_contact(message: types.Message):
    phone_number, first_name, last_name, tg_id, _ = message.contact

    new_client = {
        "first_name": first_name[1],
        "last_name": last_name[1],
        "tg_id": tg_id[1],
        "phone_number": phone_number[1],
        "discount": 0,
        "promo_code": "",
        "promo_date": None,
        "stop_promo": None,
        "attemps": 3,
    }

    clients_db.update({str(tg_id[1]): new_client})

    with open('db.json', 'w') as db:
        db.write(json.dumps(clients_db))

    # await message.answer_photo(cat)
    await message.answer(
        f"Хорошо! Испытайте удачу. У вас попыток: {new_client['attemps']}",
        reply_markup=keyboards.play_game_kb,
    )


async def main():
    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot, allowed_updates=ALLOWED_UPDATES)


if __name__ == "__main__":
    asyncio.run(main())
